//
//  BubbleView.m
//  Saas
//
//  Created by 黄志刚 on 2020/3/11.
//  Copyright © 2020 bing. All rights reserved.
//

#import "BubbleView.h"

@interface BubbleView()<UIGestureRecognizerDelegate>

@property (nonatomic,weak) UIView *targetView;
@property (nonatomic,weak) UIView *maskSuperView;

@property (nonatomic,strong) UIView *maskView;

@property (nonatomic,assign) CGRect targetViewFrame;// 点击的视图的frame（在气泡背景视图下的坐标系）
@property (nonatomic,assign) CGPoint trianglePosition;// 三角形坐标（在当前self坐标系下）
@property (nonatomic,assign) CGPoint triangleAnchorPoint;// 三角形坐标的anchorPoint（在当前self坐标系下）
@property (nonatomic,assign) CGFloat triangleSideLength;// 三角形边长

@property (nonatomic,assign) CGPoint startPoint;
@property (nonatomic,assign) CGPoint middlePoint;
@property (nonatomic,assign) CGPoint endPoint;

@property (nonatomic,assign) BubbleLocation bubbleLocation;
@property (nonatomic,assign) BubbleAlignment bubbleAlignment;
@property (nonatomic,assign) CGFloat bubbleWidth;
@property (nonatomic,assign) CGFloat bubbleHeight;
@property (nonatomic,copy) BubbleHideBlock bubbleHideBlock;


@end

@implementation BubbleView

- (instancetype)initWithLocation:(BubbleLocation)location bubbleAlignment:(BubbleAlignment)alignment width:(CGFloat)width height:(CGFloat)height hideBlock:(BubbleHideBlock)hideBlock {
    self = [super initWithFrame:(CGRectMake(0, 0, width, height))];
    self.bubbleLocation = location;
    self.bubbleAlignment = alignment;
    self.bubbleWidth = width;
    self.bubbleHeight = height;
    self.bubbleHideBlock = hideBlock;
    
    self.triangleSideLength = 15;
    self.backgroundColor = [UIColor clearColor];
    return self;
}
- (void)showWithTargetView:(UIView *)targetView maskSuperView:(UIView *)maskSuperView {
    self.targetView = targetView;
    self.maskSuperView = maskSuperView;
    
//    计算targetView在maskSuperView中的坐标系
    CGRect targetViewFrame = [targetView.superview convertRect:targetView.frame toView:maskSuperView];
    self.targetViewFrame = targetViewFrame;
    
    
    [self.maskSuperView addSubview:self.maskView];
    self.maskView.frame = self.maskSuperView.bounds;
    [self.maskView addSubview:self];
    [self addSubview:self.mainView];
    
    [self show];
}
- (void)show {
    
    [UIView animateWithDuration:0.3 animations:^{
        self.maskView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.3];
    } completion:^(BOOL finished) {
    }];
    
    
    [self calculateFrame];// 计算位置
    self.layer.position = self.trianglePosition;
    self.layer.anchorPoint = self.triangleAnchorPoint;

    self.transform = CGAffineTransformMakeScale(0.001, 0.001);
    [UIView animateWithDuration:0.3f animations:^{
        self.transform = CGAffineTransformMakeScale(1, 1);
    } completion:^(BOOL finished) {

    }];
    
}
- (void)hide {
    
    [UIView animateWithDuration:0.3 animations:^{
        self.transform = CGAffineTransformMakeScale(0.001, 0.001);
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
    [UIView animateWithDuration:0.3 animations:^{
        self.maskView.backgroundColor = [UIColor clearColor];
    } completion:^(BOOL finished) {
        [self.maskView removeFromSuperview];
    }];
    if (self.bubbleHideBlock) {
        self.bubbleHideBlock();
    }
}


- (void)drawRect:(CGRect)rect {
    
    // 设置背景色
    [self.mainView.backgroundColor set];
    //拿到当前视图准备好的画板

    CGContextRef  context = UIGraphicsGetCurrentContext();
    //利用path进行绘制三角形
    CGContextBeginPath(context);//标记
    
    [self calculateFrame];// 计算位置
    CGContextMoveToPoint(context, self.startPoint. x, self.startPoint. y);
    CGContextAddLineToPoint(context, self.middlePoint. x, self.middlePoint. y);
    CGContextAddLineToPoint(context, self.endPoint. x, self.endPoint. y);
    CGContextClosePath(context);

    CGContextDrawPath(context, kCGPathFillStroke);
    
}

- (void)calculateFrame {
    // 气泡位置
    switch (self.bubbleLocation) {
        case BubbleLocationUp:// 上
        {
            // 气泡对齐方式
            if (self.bubbleAlignment == BubbleAlignmentLeft) {// 靠左
                self.frame = CGRectMake(self.targetViewFrame.origin.x, self.targetViewFrame.origin.y-self.bubbleHeight, self.bubbleWidth, self.bubbleHeight);
                self.startPoint  = CGPointMake(self.targetViewFrame.size.width*0.5-self.triangleSideLength*0.5, self.frame.size.height-self.triangleSideLength*2*cos(M_PI/3));
            }else if (self.bubbleAlignment == BubbleAlignmentRight) {// 靠右
                self.frame = CGRectMake(self.targetViewFrame.origin.x+self.targetViewFrame.size.width-self.bubbleWidth, self.targetViewFrame.origin.y-self.bubbleHeight, self.bubbleWidth, self.bubbleHeight);
                self.startPoint  = CGPointMake(self.frame.size.width-self.targetViewFrame.size.width*0.5, self.frame.size.height-self.triangleSideLength*2*cos(M_PI/3));
            }else {// 居中
                self.frame = CGRectMake(self.targetViewFrame.origin.x+self.targetViewFrame.size.width*0.5-self.bubbleWidth*0.5, self.targetViewFrame.origin.y-self.bubbleHeight, self.bubbleWidth, self.bubbleHeight);
                self.startPoint  = CGPointMake(self.frame.size.width*0.5-self.triangleSideLength*0.5, self.frame.size.height-self.triangleSideLength*2*cos(M_PI/3));
            }
            self.mainView.frame = self.bounds;
            self.mainView.height -= self.triangleSideLength*2*cos(M_PI/3);
            
            self.middlePoint = CGPointMake(self.startPoint.x+self.triangleSideLength,self.startPoint.y);
            self.endPoint    = CGPointMake(self.startPoint.x+self.triangleSideLength*0.5,self.startPoint.y+self.triangleSideLength*2*cos(M_PI/3));
            
            self.trianglePosition = self.middlePoint;
            self.triangleAnchorPoint = CGPointMake(self.trianglePosition.x/self.frame.size.width, 1);
        }
            break;
        case BubbleLocationRight:// 右
        {
            // 气泡对齐方式
            if (self.bubbleAlignment == BubbleAlignmentTop) {// 顶部对齐
                self.frame = CGRectMake(self.targetViewFrame.origin.x+self.targetViewFrame.size.width, self.targetViewFrame.origin.y, self.bubbleWidth, self.bubbleHeight);
                self.startPoint = CGPointMake(self.triangleSideLength*2*cos(M_PI/3), self.targetViewFrame.size.height*0.5-self.triangleSideLength*0.5);
            }else if (self.bubbleAlignment == BubbleAlignmentBottom) {// 底部对齐
                self.frame = CGRectMake(self.targetViewFrame.origin.x+self.targetViewFrame.size.width, self.targetViewFrame.origin.y+self.targetViewFrame.size.height-self.bubbleHeight, self.bubbleWidth, self.bubbleHeight);
                self.startPoint = CGPointMake(self.triangleSideLength*2*cos(M_PI/3), self.frame.size.height-self.targetViewFrame.size.height*0.5-self.triangleSideLength*0.5);
            }else {// 居中
                self.frame = CGRectMake(self.targetViewFrame.origin.x+self.targetViewFrame.size.width, self.targetViewFrame.origin.y+self.targetViewFrame.size.height*0.5-self.bubbleHeight*0.5, self.bubbleWidth, self.bubbleHeight);
                self.startPoint = CGPointMake(self.triangleSideLength*2*cos(M_PI/3), self.frame.size.height*0.5-self.triangleSideLength*0.5);
            }
            self.mainView.frame = self.bounds;
            self.mainView.x += self.triangleSideLength*2*cos(M_PI/3);
            self.mainView.width -= self.triangleSideLength*2*cos(M_PI/3);
            
            self.middlePoint = CGPointMake(0,self.startPoint.y+self.triangleSideLength*0.5);
            self.endPoint    = CGPointMake(self.startPoint.x,self.startPoint.y+self.triangleSideLength);
            
            
            self.trianglePosition = self.middlePoint;
            self.triangleAnchorPoint = CGPointMake(0, self.trianglePosition.y/self.frame.size.height);
        }
            break;
        case BubbleLocationDown:// 下
        {
            // 气泡对齐方式
            if (self.bubbleAlignment == BubbleAlignmentLeft) {// 靠左
                self.frame = CGRectMake(self.targetViewFrame.origin.x, self.targetViewFrame.origin.y+self.targetViewFrame.size.height, self.bubbleWidth, self.bubbleHeight);
                self.startPoint = CGPointMake(self.targetViewFrame.size.width*0.5-self.triangleSideLength*0.5, self.triangleSideLength*2*cos(M_PI/3));
            }else if (self.bubbleAlignment == BubbleAlignmentRight) {// 靠右
                self.frame = CGRectMake(self.targetViewFrame.origin.x+self.targetViewFrame.size.width-self.bubbleWidth, self.targetViewFrame.origin.y+self.targetView.frame.size.height, self.bubbleWidth, self.bubbleHeight);
                self.startPoint = CGPointMake(self.frame.size.width-self.targetViewFrame.size.width*0.5-self.triangleSideLength*0.5, self.triangleSideLength*2*cos(M_PI/3));
            }else {// 居中
                self.frame = CGRectMake(self.targetViewFrame.origin.x+self.targetViewFrame.size.width*0.5-self.bubbleWidth*0.5, self.targetViewFrame.origin.y+self.targetView.frame.size.height, self.bubbleWidth, self.bubbleHeight);
                self.startPoint = CGPointMake(self.frame.size.width*0.5-self.triangleSideLength*0.5, self.triangleSideLength*2*cos(M_PI/3));
            }
            self.mainView.frame = self.bounds;
            self.mainView.y += self.triangleSideLength*2*cos(M_PI/3);
            self.mainView.height -= self.triangleSideLength*2*cos(M_PI/3);
            
            self.middlePoint = CGPointMake(self.startPoint.x+self.triangleSideLength*0.5, 0);
            self.endPoint = CGPointMake(self.startPoint.x+self.triangleSideLength, self.startPoint.y);
            
            self.trianglePosition = self.middlePoint;
            self.triangleAnchorPoint = CGPointMake(self.trianglePosition.x/self.frame.size.width, 0);
        }
            break;
        case BubbleLocationLeft: // 左
        {
           // 气泡对齐方式
            if (self.bubbleAlignment == BubbleAlignmentTop) {// 顶部对齐
                self.frame = CGRectMake(self.targetViewFrame.origin.x-self.bubbleWidth, self.targetViewFrame.origin.y, self.bubbleWidth, self.bubbleHeight);
                self.startPoint = CGPointMake(self.frame.size.width-self.triangleSideLength*2*cos(M_PI/3), self.targetViewFrame.size.height*0.5-self.triangleSideLength*0.5);
            }else if (self.bubbleAlignment == BubbleAlignmentBottom) {// 底部对齐
                self.frame = CGRectMake(self.targetViewFrame.origin.x-self.bubbleWidth, self.targetViewFrame.origin.y+self.targetViewFrame.size.height-self.bubbleHeight, self.bubbleWidth, self.bubbleHeight);
                self.startPoint = CGPointMake(self.frame.size.width-self.triangleSideLength*2*cos(M_PI/3), self.frame.size.height-self.targetViewFrame.size.height*0.5-self.triangleSideLength*0.5);
            }else {// 居中
                self.frame = CGRectMake(self.targetViewFrame.origin.x-self.bubbleWidth, self.targetViewFrame.origin.y+self.targetViewFrame.size.height*0.5-self.bubbleHeight*0.5, self.bubbleWidth, self.bubbleHeight);
                self.startPoint = CGPointMake(self.frame.size.width-self.triangleSideLength*2*cos(M_PI/3), self.frame.size.height*0.5-self.triangleSideLength*0.5);
            }
            self.mainView.frame = self.bounds;
            self.mainView.width -= self.triangleSideLength*2*cos(M_PI/3);
            
            self.middlePoint = CGPointMake(self.startPoint.x, self.startPoint.y+self.triangleSideLength);
            self.endPoint = CGPointMake(self.startPoint.x+self.triangleSideLength*2*cos(M_PI/3), self.startPoint.y+self.triangleSideLength*0.5);
            
            self.trianglePosition = self.middlePoint;
            self.triangleAnchorPoint = CGPointMake(1, self.trianglePosition.y/self.frame.size.height);
        }
            break;
            
        default:
            break;
    }
}


- (UIView *)maskView {
    if (!_maskView) {
        _maskView = [[UIView alloc] init];
        _maskView.backgroundColor = [UIColor clearColor];
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(maskClick)];
        [_maskView addGestureRecognizer:tap];
        _maskView.userInteractionEnabled = YES;
        tap.delegate = self;
    }
    return _maskView;
}

- (UIView *)mainView {
    if (!_mainView) {
        _mainView = [[UIView alloc] init];
        _mainView.clipsToBounds = YES;
        _mainView.layer.cornerRadius = 1;
        _mainView.backgroundColor = [UIColor whiteColor];
    }
    return _mainView;
}


#pragma mark --------- Action ----------
#pragma mark - UIGestureRecognizerDelegate
//* 解决gestureRecognizerTap点击手势和tableView cell点击手势的冲突 *
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {
        return NO;
    }
    return YES;
}
- (void)maskClick {
    [self hide];
}

@end
